package org.dtrd.modules.archive.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.dtrd.config.system.Constant;
import org.dtrd.modules.archive.service.IDtrdEntRdPhysicalService;
import org.dtrd.modules.dict.service.IDtrdEntRdDicDistrictService;
import org.dtrd.modules.doctor.service.IDtrdRlDoctorPatientService;
import org.dtrd.modules.patient.entity.bean.PatientBasicAndFamilyInfo;
import org.dtrd.modules.patient.entity.bean.PatientInfo;
import org.dtrd.modules.archive.entity.po.DtrdEntRdArchiveBasic;
import org.dtrd.modules.archive.entity.po.DtrdEntRdArchiveBasicFamily;
import org.dtrd.modules.patient.entity.po.DtrdEntRdPatient;
import org.dtrd.modules.patient.entity.request.PatientRequest;
import org.dtrd.modules.archive.mapper.DtrdEntRdArchiveBasicMapper;
import org.dtrd.modules.archive.service.IDtrdEntRdArchiveBasicFamilyService;
import org.dtrd.modules.archive.service.IDtrdEntRdArchiveBasicService;
import org.dtrd.modules.patient.service.IDtrdEntRdPatientService;
import org.dtrd.modules.questionnaire.entity.bean.PatientBasicInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 * @author 萧
 * @date 2021-10-01 22:47:26
 **/
@Service
@DS("multi-datasource1")
@Slf4j
public class DtrdEntRdArchiveBasicServiceImpl extends ServiceImpl<DtrdEntRdArchiveBasicMapper, DtrdEntRdArchiveBasic> implements IDtrdEntRdArchiveBasicService {

    @Autowired
    private IDtrdEntRdPatientService patientService;
    @Autowired
    private IDtrdEntRdArchiveBasicFamilyService basicFamilyService;
    @Autowired
    private IDtrdEntRdPhysicalService physicalService;
    @Autowired
    private IDtrdEntRdDicDistrictService districtInfoService;
    @Autowired
    private IDtrdRlDoctorPatientService doctorPatientRlService;

    @Override
    public Integer getPatientArchiveInfoPercent(Integer patientId) {
        return baseMapper.selectPatientArchiveInfoPercent(patientId);
    }

    @Override
    public void removeByPatientIds(Set<Integer> patientIds) {
        baseMapper.deleteByPatientIds(patientIds);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean saveOrUpdatePatientInfo(PatientBasicAndFamilyInfo info) {
        Date now = new Date();
        DtrdEntRdArchiveBasic basicMobileCheck = baseMapper.selectOne(new LambdaQueryWrapper<>(DtrdEntRdArchiveBasic.class)
                .eq(DtrdEntRdArchiveBasic::getMobile, info.getPatientMobile())
                .eq(DtrdEntRdArchiveBasic::getIsDel, 0)
                .last("limit 1")
        );
        PatientInfo patientMobileCheck = patientService.selectByMobile(info.getPatientMobile());
        Integer patientId;
        // 修改
        if (info.getPatientId() != null) {
            log.info("edit patient");
            patientId = info.getPatientId();
            // 更新 basic 表
            // 查找手机号是否已经被其他人记录
            if (basicMobileCheck != null && !Objects.equals(basicMobileCheck.getPatientId(), patientId)) {
                log.info("DtrdEntRdBasicServiceImpl.saveOrUpdatePatientInfo.[info] basicMobileCheck exist , basicMobileCheck.getPatientId(), patientId not the same");
                return false;
            }
            if (patientMobileCheck != null && !Objects.equals(patientMobileCheck.getDataId(), patientId)) {
                log.info("DtrdEntRdBasicServiceImpl.saveOrUpdatePatientInfo.[info] patientMobileCheck exist ,patientMobileCheck.getDataId(), patientId not the same ");
                return false;
            }
            DtrdEntRdArchiveBasic basic = new DtrdEntRdArchiveBasic().parseFromDTO(info);
            basic.setCreateTime(now);
            // 判断是否存在basic记录，如不存在则新增一条
            LambdaUpdateWrapper<DtrdEntRdArchiveBasic> basicUpdateWrapper = Wrappers.lambdaUpdate(DtrdEntRdArchiveBasic.class)
                    .eq(DtrdEntRdArchiveBasic::getPatientId, patientId);
            this.saveOrUpdate(basic, basicUpdateWrapper);
            // 更新 patient 表
            DtrdEntRdPatient patient = info.toPoPatient();
            patientService.saveOrUpdate(patient);
            // 更新或修改 basicFamily 表
            LambdaQueryWrapper<DtrdEntRdArchiveBasicFamily> familyQueryWrapper = Wrappers.lambdaQuery(DtrdEntRdArchiveBasicFamily.class)
                    .eq(DtrdEntRdArchiveBasicFamily::getPatientId, info.getPatientId())
                    .eq(DtrdEntRdArchiveBasicFamily::getIsDel, 0);
            DtrdEntRdArchiveBasicFamily queryFamily = basicFamilyService.getOne(familyQueryWrapper);
            if (queryFamily == null) {
                queryFamily = new DtrdEntRdArchiveBasicFamily().init();
            }
            queryFamily.parseFromDto(info);
            basicFamilyService.saveOrUpdate(queryFamily);
        } else {
            // 新增
            // 先存 patient 表
            if (patientMobileCheck != null || basicMobileCheck != null) {
                return false;
            }
            DtrdEntRdPatient patient = info.toPoPatient();
            patient.setCreateTime(now);
            // 设置默认的机构编码, 暂时为 AO1
            if (info.getOrgCode() != null) {
                patient.setOrgCode(info.getOrgCode());
            } else {
                patient.setOrgCode("A01");
            }
            patientService.save(patient);
            info.setPatientId(patient.getDataId());
            patientId = patient.getDataId();

            DtrdEntRdArchiveBasic basic = new DtrdEntRdArchiveBasic().parseFromDTO(info);
            basic.setCreateTime(now);
            baseMapper.insert(basic);
            // 存 basicFamily 表
            DtrdEntRdArchiveBasicFamily basicFamily = new DtrdEntRdArchiveBasicFamily().parseFromDto(info);
            basicFamilyService.save(basicFamily);
        }
        physicalService.saveOrUpdatePatientInfo(patientId, info.getHeight(), info.getWeight());
        return true;
    }

    @Override
    public boolean saveOrUpdatePatientInfo(PatientBasicInfo info) {
        DtrdEntRdArchiveBasic archiveBasic = getPatientBasicInfoByPatientId(info.getPatientId());
        if (archiveBasic == null) {
            archiveBasic = new DtrdEntRdArchiveBasic().init();
        }
        archiveBasic.parseFromDTO(info);
        return saveOrUpdate(archiveBasic);
    }

    @Override
    public List<PatientBasicAndFamilyInfo> getPatientBasicInfoByRequest(PatientRequest request) {
        List<PatientBasicAndFamilyInfo> infos = baseMapper.selectPatientBasicInfoByRequest(request);
        if (CollectionUtil.isNotEmpty(infos)) {
            for (PatientBasicAndFamilyInfo info : infos) {
                Integer patientId = info.getPatientId();
                // 查询 patient 表信息
                LambdaQueryWrapper<DtrdEntRdPatient> wrapper1 = Wrappers.lambdaQuery(DtrdEntRdPatient.class)
                        .eq(DtrdEntRdPatient::getIsDel, 0)
                        .eq(DtrdEntRdPatient::getDataId, patientId);
                DtrdEntRdPatient patient = patientService.selectPoByPatientId(patientId);
                if (patient != null) {
                    info.parseFromPO(patient);
                    Date birthday = patient.getPatientsBirthday();
                    if (birthday != null) {
                        info.setAge(DateUtil.ageOfNow(birthday));
                    }
                }
                // 查 basic 表信息
                LambdaQueryWrapper<DtrdEntRdArchiveBasic> wrapper2 = Wrappers.lambdaQuery(DtrdEntRdArchiveBasic.class)
                        .eq(DtrdEntRdArchiveBasic::getIsDel, 0)
                        .eq(DtrdEntRdArchiveBasic::getPatientId, patientId);
                DtrdEntRdArchiveBasic basic = getOne(wrapper2);
                if (basic != null) {
                    info.parseFromPO(basic);
                }
                // 查询 basicFamily表信息
                LambdaQueryWrapper<DtrdEntRdArchiveBasicFamily> familyQueryWrapper = Wrappers.lambdaQuery(DtrdEntRdArchiveBasicFamily.class)
                        .eq(DtrdEntRdArchiveBasicFamily::getIsDel, 0)
                        .eq(DtrdEntRdArchiveBasicFamily::getPatientId, patientId)
                        .last("limit 1");
                DtrdEntRdArchiveBasicFamily family = basicFamilyService.getOne(familyQueryWrapper);
                if (family != null) {
                    info.parseFromPO(family);
                }
                // 翻译字典
                Integer sex = info.getPatientSex();
                if (sex != null) {
                    info.setPatientSexText(Constant.Sex.valueOf(sex).getName());
                }
                // 劳动程度
                Integer occupation = info.getOccupation();
                if (occupation != null) {
                    info.setOccupationText(Constant.Occupation.valueOf(occupation).getName());
                }
                // 教育程度
                Integer education = info.getEducation();
                if (education != null) {
                    info.setEducationText(Constant.Education.valueOf(education).getName());
                }
                // 是否卧病在床
                Integer isSickbed = info.getIsSickbed();
                if (isSickbed != null) {
                    info.setIsSickedText(Constant.IsSicked.valueOf(isSickbed).getName());
                }
                // 备孕
                Integer gestation = info.getGestation();
                if (gestation != null) {
                    info.setGestationText(Constant.Gestation.valueOf(gestation).getName());
                }
                // 患者属性
                Integer patientProperty = info.getPatientProperty();
                if (patientProperty != null) {
                    info.setPatientPropertyText(Constant.PatientProperty.valueOf(patientProperty).getName());
                }
                // 付款模式
                Integer payMode = info.getPayMode();
                if (payMode != null) {
                    info.setPayModeText(Constant.PayMode.valueOf(payMode).getName());
                }
                // 婚姻状态
                Integer maritalStatus = info.getMaritalStatus();
                if (maritalStatus != null) {
                    info.setMaritalStatusText(Constant.MaritalStatus.valueOf(maritalStatus).getName());
                }
                // 家属关系
                Integer familyRelation = info.getFamilyRelation();
                if (familyRelation != null) {
                    info.setFamilyRelationText(Constant.FamilyRelation.valueOf(familyRelation).getName());
                }
                // 省份
                Integer provinceId = info.getProvinceId();
                if (provinceId != null) {
                    info.setProvinceText(districtInfoService.getDistrictNameById(provinceId));
                }
                // 城市
                Integer cityId = info.getCityId();
                if (cityId != null) {
                    info.setCity(districtInfoService.getDistrictNameById(cityId));
                }
            }
        }
        return infos;
    }

    @Override
    public DtrdEntRdArchiveBasic getPatientBasicInfoByPatientId(Integer patientId) {
        return baseMapper.getPatientBasicInfoByPatientId(patientId);
    }
}
